#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

#if 1

#include <stdio.h>
#include <QThread>
#include <QElapsedTimer>
#include <QCoreApplication>

#include <QMidiOut.h>
#include <QMidiFile.h>

class MidiPlayer : public QThread
{
    Q_OBJECT
public:
    MidiPlayer(QMidiFile* file, QMidiOut* out)
    {
        midi_file = file;
        midi_out = out;
    }

private:
    QMidiFile* midi_file;
    QMidiOut* midi_out;

protected:
    void run()
    {
        QElapsedTimer t;
        t.start();
        QList<QMidiEvent*> events = midi_file->events();
        for (QMidiEvent* e : events) {
            if (e->type() != QMidiEvent::Meta) {
                qint64 event_time = midi_file->timeFromTick(e->tick()) * 1000;

                qint32 waitTime = event_time - t.elapsed();
                if (waitTime > 0) {
                    msleep(waitTime);
                }
                if (e->type() == QMidiEvent::SysEx) {
                    // TODO: sysex
                } else {
                    qint32 message = e->message();
                    midi_out->sendMsg(message);
                }
            }
        }

        midi_out->disconnect();
    }
};


#endif

QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();

private slots:
    void on_pushButton_clicked();

    void on_pushButton_2_clicked();

    void on_pushButton_3_clicked();

    void on_pushButton_4_clicked();

private:
    Ui::Widget *ui;
};
#endif // WIDGET_H
